package com.yjf.ljr.util;

import android.text.Editable;
import android.text.Selection;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.widget.EditText;

public class PasswordWatcher implements TextWatcher {

	private EditText mEdtContent;
	private CharSequence temp;
	private int editStart;
	private int editEnd;

	public PasswordWatcher(EditText editText) {
		this.mEdtContent = editText;
	}

	@Override
	public void onTextChanged(CharSequence s, int start, int before, int count) {
		temp = s;
	}

	@Override
	public void beforeTextChanged(CharSequence s, int start, int count, int after) {
	}

	@Override
	public void afterTextChanged(Editable s) {
		if(TextUtils.isEmpty(temp)) {
			return;
		}
		editStart = mEdtContent.getSelectionStart();
		editEnd = mEdtContent.getSelectionEnd();
		for (int i = 0; i < s.length(); i++) {
			String c = s.charAt(i) + "";
			if (isLetterDigitOrChinese(c)) {
				s.delete(i, i + 1);
			}
		}
		if (temp.length() > 25) {
			s.delete(editStart - 1, editEnd);
			mEdtContent.setText(s);
			Selection.setSelection(s, s.length());
		} else if (temp.length() == 25) {
			Selection.setSelection(s, s.length());
		}
	}

	// 判断字符串是否由汉字组成
	public static boolean isLetterDigitOrChinese(String str) {
		String regex = "[\u4e00-\u9fa5]";
		return str.matches(regex);
	}
}
